<?php

namespace app\bll;

use app\validate\UserMessage as ValidateUserMessage;
use Exception;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use support\Db;

class UserMessage
{

    /**
     * 添加信件
     *
     * @param array $data
     * @return integer
     */
    public function add(array $data): int
    {
        //验证
        $validateUserMessage = new ValidateUserMessage();
        if (!$validateUserMessage->check($data)) {
            throw new Exception($validateUserMessage->getSimpleError());
        }
        $data['sendtime'] = time();
        return Db::table('frame_user_message')->insert($data);
    }

    /**
     * 未读信件数量
     *
     * @return integer
     */
    public function unreadCount(int $recipient): int
    {
        return Db::table('frame_user_message')
            ->where('recipient', '=', $recipient)
            ->where('isread', '=', 0)
            ->count();
    }


    /**
     * 设为已读
     *
     * @param int|array $ids
     * @param int $recipient
     * @return integer
     */

    public function setRead(int|array $ids, int $recipient): int
    {

        if (!is_array($ids)) {
            $ids = [$ids];
        }

        return Db::table('frame_user_message')
            ->whereIn('id',  $ids)
            ->where('recipient', '=', $recipient)
            ->update(['isread' => 1]);
    }

    /**
     * 全部设为已读
     *
     * @param int $recipient
     * @return integer
     */
    public function setAllRead(int $recipient): int
    {
        return Db::table('frame_user_message')
            ->where('recipient', '=', $recipient)
            ->update(['isread' => 1]);
    }

    /**
     * 删除信件
     *
     * @param integer|array $ids
     * @param integer $recipient
     * @return integer
     */
    public function delete(string|int|array $ids, int $recipient): int
    {
        if (!is_array($ids)) {
            $ids = [$ids];
        }
        if (is_string($ids)) {
            $ids = explode(',', $ids);
        }
        return Db::table('frame_user_message')
            ->whereIn('id',  $ids)
            ->where('recipient', '=', $recipient)
            ->delete();
    }


    /**
     * 分页查询
     *
     * @param integer $recipient
     * @param integer $pagesize
     * @return LengthAwarePaginator
     */
    public function paginator(
        int $recipient,
        int $pagesize = 20
    ): LengthAwarePaginator {
        return  Db::table('frame_user_message')
            ->where('recipient', '=', $recipient)
            ->orderBy('id', 'desc')
            ->paginate($pagesize);
    }
}
